package com.mywang.weitravel.modules.mine;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.mywang.weitravel.R;
import com.mywang.weitravel.base.BaseFragment;
import com.mywang.weitravel.base.MyApplication;
import com.mywang.weitravel.common.Contacts;
import com.mywang.weitravel.model.UserBean;
import com.mywang.weitravel.modules.image.GlideImageEngine;
import com.mywang.weitravel.util.PreferencesUtil;
import com.mywang.weitravel.util.ScreenUtil;

import java.util.List;

import androidx.core.content.ContextCompat;
import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * Created by wangmingyun on 2019/12/5.
 */
public class MineFragment extends BaseFragment<MinePresenter> implements MineContract.View, CustomAdapt {

    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.tv_sign)
    TextView tvSign;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;
    @BindView(R.id.tv_collection)
    TextView tvCollection;
    @BindView(R.id.tv_message)
    TextView tvMessage;
    @BindView(R.id.tv_set_password)
    TextView tvSetPassword;
    @BindView(R.id.tv_clean)
    TextView tvClean;
    @BindView(R.id.iv_user_head)
    ImageView ivUserHead;
    @BindView(R.id.tv_cache)
    TextView tvCache;
    @BindView(R.id.tv_logout)
    TextView tvLogout;
    private DialogChoosePhoto dialogChoosePhoto;
    private PictureParameterStyle parameterStyle = new PictureParameterStyle();

    @Override
    protected MinePresenter initPresenter() {
        return new MinePresenter(this);
    }

    @Override
    protected int getFragmentLayoutID() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        Object userInfo = PreferencesUtil.getInstance(MyApplication.getApplication()).getObject(Contacts.SP_USER_INFO);
        if (userInfo instanceof UserBean && PreferencesUtil.getInstance(MyApplication.getApplication()).isLogin()) {
            String avatarUrl = ((UserBean) userInfo).getThumb();
            if (!TextUtils.isEmpty(avatarUrl)) {
                GlideImageEngine.getInstance().loadImage(avatarUrl, ivUserHead, R.mipmap.icon_head_default, ScreenUtil.dp2px(51));
            }
            String username = ((UserBean) userInfo).getUsername();
            if (!TextUtils.isEmpty(username)) {
                tvUserName.setText(username);
            }
        }
        initSelectStyle();
        dialogChoosePhoto = new DialogChoosePhoto(getActivity()) {
            @Override
            public void btnPickBySelect() {
                PictureSelector.create(MineFragment.this)
                        .openGallery(PictureMimeType.ofImage())
                        .setPictureStyle(parameterStyle)
                        .loadImageEngine(GlideImageEngine.getInstance())
                        .maxSelectNum(1)
                        .compress(true)
                        .compressQuality(80)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void btnPickByTake() {
                PictureSelector.create(MineFragment.this)
                        .openCamera(PictureMimeType.ofImage())
                        .setPictureStyle(parameterStyle)
                        .enableCrop(false)
                        .compressQuality(80)
                        .loadImageEngine(GlideImageEngine.getInstance())
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.calculateCacheSize();
        mPresenter.getUserInfo();
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mPresenter.calculateCacheSize();
        }
    }

    @OnClick({R.id.iv_message, R.id.tv_sign, R.id.tv_user_name, R.id.tv_collection, R.id.tv_message, R.id.tv_set_password, R.id.ll_clean, R.id.iv_user_head, R.id.tv_logout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_message:
                break;
            case R.id.tv_user_name:
                if (goLoginActivity(getActivity())) {
                    UserInfoActivity.launch(getActivity());
                }
                break;
            case R.id.tv_collection:
                if (goLoginActivity(getActivity())) {
                    CollectionActivity.launch(getActivity());
                }
                break;
            case R.id.tv_sign:
                if (goLoginActivity(getActivity())) {
                    mPresenter.sign();
                }
                break;
            case R.id.tv_message:
                break;
            case R.id.tv_set_password:
                if (goLoginActivity(getActivity())) {
                    ResetPwdActivity.launch(getActivity());
                }
                break;
            case R.id.ll_clean:
                mPresenter.cleanCache();
                break;
            case R.id.iv_user_head:
                if (goLoginActivity(getActivity())) {
                    dialogChoosePhoto.show();
                }
                break;
            case R.id.tv_logout:
                PreferencesUtil.getInstance(getActivity()).setLogin(false);
                PreferencesUtil.getInstance(getActivity()).saveParam(Contacts.SP_USER_INFO, new UserBean());
                tvUserName.setText("登录/注册");
                if (getActivity() != null) {
                    tvUserName.setTextColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
                }
                ivUserHead.setImageResource(R.mipmap.icon_head_default);
                tvSign.setText("立即签到");
                tvJifen.setText("0（积分）");
                break;
        }
    }

    private void initSelectStyle() {
        if (getActivity() != null) {
            parameterStyle.pictureStatusBarColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureTitleBarBackgroundColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.picturePreviewTextColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureCompleteTextColor = ContextCompat.getColor(getActivity(), R.color.color_00f19d);
            parameterStyle.pictureLeftBackIcon = R.mipmap.icon_left_back_white;
            parameterStyle.pictureExternalPreviewGonePreviewDelete = true;
            parameterStyle.isOpenCompletedNumStyle = true;
        }
    }

    @Override
    public void signSuccessful() {
        ToastUtils.showShort("签到成功");
        mPresenter.getUserInfo();
        tvSign.setText("已签到");
        tvSign.setClickable(false);
    }

    @Override
    public void calculateCacheSizeSuccessful(String cacheStr) {
        tvCache.setText(cacheStr);
    }

    @Override
    public void cleanCacheSuccessful() {
        tvCache.setText("0KB");
        ToastUtils.showShort("已清除缓存");
    }

    @Override
    public void getUserInfoSuccessful(UserBean userBean) {
        PreferencesUtil.getInstance(MyApplication.getApplication()).saveParam(Contacts.SP_USER_INFO, userBean);
        GlideImageEngine.getInstance().loadImage(userBean.getAvatar(), ivUserHead, R.mipmap.icon_head_default, ScreenUtil.dp2px(51));
        tvUserName.setText(userBean.getUsername());
        tvJifen.setText(userBean.getScore() + "（积分）");
        if (userBean.isSign()) {
            tvSign.setText("已签到");
            tvSign.setClickable(false);
        } else {
            tvSign.setText("立即签到");
            tvSign.setClickable(true);
        }
        if (getActivity() != null) {
            tvUserName.setTextColor(ContextCompat.getColor(getActivity(), R.color.color_2d3240));
        }
    }

    public boolean isBaseOnWidth() {
        if (ScreenUtil.isScreenSizeLarge(getActivity())) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public float getSizeInDp() {
        if (ScreenUtil.isScreenSizeLarge(getActivity())) {
            return 667;
        } else {
            return 360;
        }
    }

    @Override
    public void uploadAvatarSuccessful(String url) {
        ToastUtils.showShort("修改头像成功");
        mPresenter.getUserInfo();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!selectList.isEmpty()) {
                        mPresenter.uploadAvatar(selectList.get(0).getPath());
                    }
                    break;
            }
        }
    }
}
